/*
 * Copyright 2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.lin.cms.logging;

import java.text.DecimalFormat;
import java.text.NumberFormat;

import org.aopalliance.intercept.MethodInvocation;

/**
 * Default implementation of The MethodInvocationLogger.
 * 
 * @author Byeongkil Woo
 */
public class DefaultMethodInvocationLogger implements MethodInvocationLogger {

	public static final NumberFormat timeFormat = new DecimalFormat("###,###");

	private String indent = "    ";

	public void setIndent(String indent) {
		this.indent = indent;
	}

	public String invocationMessage(MethodInvocation invocation) {
		String message = getDepthString() + "----> " + getInvocationMessage(invocation);

		return message;
	}

	public String processMessage(MethodInvocation invocation, Object returnValue, long millis) {
		String fullClassName = "void";

		if (returnValue != null) {
			fullClassName = returnValue.getClass().getName();
		}

		String message = getDepthString() + "<---- " + fullClassName + ": " + returnValue + " [" + timeFormat.format(millis) + "ms]";

		return message;
	}

	public String onThrowingMessage(MethodInvocation invocation, Throwable t) {
		String message = "<<<<< " + t;

		return message;
	}

	private String getInvocationMessage(MethodInvocation invocation) {
		Class<?> clazz = invocation.getThis().getClass();
		String fullClassName = clazz.getName();
		String methodName = invocation.getMethod().getName();
		Object[] arguments = invocation.getArguments();

		String message = fullClassName + "." + methodName + "(";

		boolean firstArgument = true;
		for (int i = 0; i < arguments.length; i++) {
			Object argument = arguments[i];

			if (!firstArgument) {
				message += ", ";
			}
			message += argument;
			firstArgument = false;
		}

		message += ")";

		return message;
	}

	private String getDepthString() {
		String ds = "";

		int depth = MethodInvocationInfoInterceptor.getCurrentDepth();
		for (int i = 0; i < depth; i++) {
			ds += indent;
		}

		return ds;
	}

}
